package bblnamed

import (
	"code.google.com/p/go-uuid/uuid"
	"logger"
	"math/rand"
	"time"
)

var log *logger.Logger // = logger.NewLogger("stdout", "[volume] ", "info")

func UUID() string {
	return uuid.NewUUID().String()
}

func Rand() int {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return r.Intn(100000000)
}

// func Hash(data []byte) uint32 {
// 	return crc32.ChecksumIEEE(data)
// }

func Timestamp() uint64 {
	return uint64(time.Now().Unix())
}

func Sleep(millisecond int) {
	time.Sleep(time.Duration(millisecond) * time.Millisecond)
}

func Start(conf string) (err error) {
	if err = init_config(conf); err != nil {
		return err
	}
	if err = init_log(); err != nil {
		return err
	}
	if err = init_cluster_server(); err != nil {
		server = nil
		return err
	}
	go server.Serve()
	return nil
}

func Stop() {
	if server != nil {
		server.Stop()
		server = nil
	}
}

func init_log() error {
	logg, err := logger.NewLogger(server_conf.LogFile, "[cluster] ", server_conf.LogLevel)
	if err != nil {
		return err
	}
	log = logg
	return nil
}

var server *ClusterServer

func init_cluster_server() error {
	server = &ClusterServer{
		Listen:     server_conf.Listen,
		Name:       server_conf.Name,
		Slaves:     server_conf.Slaves,
		Master:     server_conf.Master,
		Workdir:    server_conf.Workdir,
		Replicas:   server_conf.Replicas,
		Passphrase: server_conf.Passphrase,
		//Clients:    gateway_conf,
	}
	return server.Init()
}
